
<template>
  <div class="main">
    <PureTableBar title="价款支付列表" class="list_hei">
      <template #buttons>
        <el-button type="primary" @click="DialogVisible = true">获取资产池收入 </el-button>
      </template>
      <template v-slot="{ size, checkList }">
        <pure-table border align-whole="center" showOverflowTooltip table-layout="auto" adaptive size="small"
          :data="dataList" max-height="600" :columns="columns" :checkList="checkList" :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }">
        </pure-table>
      </template>
    </PureTableBar>
  </div>

  <ReDialog :width="800" :height="420" :models="DialogVisible" @Closes="DialogVisible = false">
    <template #header>
      <h2 style="text-align: center;">获取收入窗口</h2>
    </template>
    <template #main>
      <div class="fz-14">
        <div style="margin: 20px 0;">
          资产证券化项目：<el-select placeholder="请选择资产证券化项目" v-model="filterSelectId" style="width:40%">
            <el-option v-for="item in filterDataList" :key="item.assetPoolId" :label="item.assetSecuritizationName"
              :value="item.assetPoolId" @click="filterProject(item)" />
          </el-select>
        </div>
        <div>
          <div>
            <p style="padding: 0 45px;">{{ formData.projectName }}基础资产池在产品期限内共产生收入{{
              formData.accountReceivableAmount }}元，计划管理人需要用这笔资金去支付发行证券的本息，还有支付融资过程中个服务机构的费用</p>
          </div>
        </div>
        <p style="margin-top: 50px;"></p>
      </div>
      <el-form label-width="120px">
        <el-form-item label="转账方：">
          电商平台
        </el-form-item>
        <el-form-item label="收款方：">
          {{ payinterestData.spvName }}
        </el-form-item>
        <el-form-item label="转支付金额：">
          {{ formData.accountReceivableAmount
          }}元
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="saveToSpv()"> 确定 </el-button>
        <el-button @click="DialogVisible = false"> 取消 </el-button>
      </span>
    </template>
  </ReDialog>
</template>
<script setup lang='ts'>
import { emitter } from "@/utils/mitt";
import {
  CirclePlusFilled
} from "@element-plus/icons-vue"; import {
  GetSPVName,
  GetPassAuditProjectName,
  GetExcessCollateral,
  FinancialTransactionsUsersGetByUsername,
  TransactionsOredrsCreate,
  GetSmallLoanCreditbalance,
  GetInfoByAssetTransferId,
  GetByAssetTransferId,
  TransferToInvestor,
  UpdateSpvBanlncerById,
  IsTransferService,
  SecuritiesServiceChargCreate,
  GetSecuritiesHaveBeenPaid
} from "@/api/stu/SupplyChainFinance";
import { ElMessage } from "element-plus";
import qs from "qs";
import { useRoute } from "vue-router";
import { ref, reactive, onMounted, watch } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";

const formData = reactive({
  accountReceivableAmount: '',
  projectName: '',
})
const route = useRoute();

const payinterestData = reactive({
  date: '',
  issuanceSize: '',
  projectName: '',
  rate: '',
  spvName: '',
  payMoney: ''
})
const columns: TableColumnList = [
  {
    label: "序号",
    type: "index",
    fixed: "left",
    minWidth: 50
  },
  {
    label: "项目名称",
    prop: "securityCreditRatingName",
  },
  {
    label: "转账方",
    prop: "fromName",
  },
  {
    label: "收款方",
    prop: "toAccount",
  },
  {
    label: "金额（元）",
    prop: "banlance",
  },
];
const selectItem = ref()//选中的项目
const showCase = ref(true)
const filterDataList = ref([])
const filterSelectId = ref('')
const DialogVisible = ref(false)
const dataList = ref([])


async function saveToSpv() {
  if (!filterSelectId.value) {
    ElMessage.warning('请选择资产证券化项目')
    return
  }
  const params = qs.stringify({
    fromName: "资产池",
    toAccount: "spv",
    type: 3,
    securityCreditRatingId: selectItem.value.securityCreditRatingId,
  })
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
  }
  let res = await IsTransferService(params, data)
  if (!res.data) {
    const params = qs.stringify({ id: filterSelectId.value, taskId: route.query.taskId, planId: route.query.planId, assetSecuritizationName: selectItem.value.assetSecuritizationName })
    let res = await UpdateSpvBanlncerById(params)
    if (res.success) {
      ElMessage.success(`成功获取${formData.projectName}基础资产池产生的收入${formData.accountReceivableAmount}`)
      const data = {
        securitiesServiceChargeId: "",
        taskId: route.query.taskId,
        planId: route.query.planId,
        securityCreditRatingId: selectItem.value.securityCreditRatingId,
        fromName: "资产池",
        toAccount: "spv",
        banlance: formData.accountReceivableAmount,
        type: 3
      }
      setTimeout(() => {
        getList()
      }, 500);
      let res4 = await SecuritiesServiceChargCreate(data)
      emitter.emit('refreshMoney')
      cancelTransfer()
    } else {
      ElMessage.error(res.msg)
    }
  } else {
    ElMessage.warning('该项目已获取资产池收入，请勿重复操作！')
  }
}
function cancelTransfer() {
  formData.accountReceivableAmount = ''
  formData.projectName = ''
  payinterestData.date = ''
  payinterestData.issuanceSize = ''
  payinterestData.projectName = ''
  payinterestData.rate = ''
  payinterestData.spvName = ''
  payinterestData.payMoney = ''
  filterSelectId.value = ''
  DialogVisible.value = false
}
async function filterProject(item) {
  selectItem.value = item
  formData.projectName = item.assetSecuritizationName
  payinterestData.projectName = item.assetSecuritizationName
  //获取资产池余额（应付账款）
  const data = qs.stringify({
    assetPoolId: item.assetPoolId,
  })
  let res = await GetSmallLoanCreditbalance(data)
  if (res.success) {
    formData.accountReceivableAmount = res.data
  } else {
    ElMessage.error(res.msg)
  }
  //获取票面利率
  const data1 = qs.stringify({
    assetTransferId: item.assetTransferId
  })
  let res1 = await GetExcessCollateral(data1)
  if (res1.success) {
    payinterestData.issuanceSize = res1.data
  } else {
    ElMessage.warning('请先完成超额抵押增信方式')
  }
  //收益率
  let res2 = await GetInfoByAssetTransferId(data1)
  if (res2.success) {
    payinterestData.rate = res2.data.expectedIssueRate
  } else {
    ElMessage.warning(res2.msg)
  }
  let res4 = await GetSPVName(data1)
  if (res4.success) {
    payinterestData.spvName = res4.data.spvCompanyName
  } else {
    ElMessage.warning(res4.msg)
  }
  let res5 = await GetByAssetTransferId(data1)
  if (res5.success) {
    payinterestData.date = res5.data.productTerm
  } else {
    ElMessage.warning(res5.msg)
  }
  payinterestData.payMoney = Number(payinterestData.issuanceSize * (payinterestData.rate / 360 / 100) * payinterestData.date).toFixed(2)
}
onMounted(async () => {
  getList()
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
  }
  let res = await GetPassAuditProjectName(data)
  if (res.success) {
    filterDataList.value = res.data
  } else {
    ElMessage.error(res.msg)
  }
})


async function getList() {
  const params = qs.stringify({
    fromName: "资产池",
    toAccount: "spv",
    type: 3
  })
  const data = {
    taskId: route.query.taskId,
    planId: route.query.planId,
  }
  let res = await GetSecuritiesHaveBeenPaid(params, data)
  if (res.success) {
    dataList.value = res.data
  } else {
    ElMessage.error(res.msg)
  }
}

</script>
<style scoped lang="scss">
@import url(@/style/CreditComm.scss);


:deep(.el-form-item__label) {
  font-weight: 700;
  font-size: 14px;
}

.fz-14 {
  font-size: 14px;
}
</style>
